<template>
  <!-- :class="show ? 'show' : ''" @tap="hideModal" -->
  <view>
    <wd-popup
      class="cu-modal"
      :closeOnClickModal="false"
      customStyle="width: '90vw',border-radius: '15rpx'"
      custom-class="cu-modal"
      v-model="state.showDia"
    >
      <view class="cu-dialog bg-white" @tap.stop="">
        <view class="cu-bar flex items-center">
          <view class="action" @tap="hideModal">取消</view>
          <text class="action" style="margin-right: 30rpx; font-size: 30rpx" @tap="makeSure">
            确定
          </text>
        </view>
        <view class="checked">
          当前选择：
          <scroll-view :scroll-left="state.scrollLeft" scroll-with-animation scroll-x>
            <text
              v-for="(item, index) in checked"
              :key="index"
              class="text-blue"
              @click="cancelThis(index)"
            >
              {{ item.personName }}
              <text class="cuIcon-roundclose text-gray"></text>
            </text>
          </scroll-view>
        </view>
        <swiper class="swiper" @change="getData">
          <swiper-item>
            <input
              class="search"
              v-model="state.realName"
              @input="onSearchInput"
              placeholder="根据关键词查询"
            />

            <view class="dept_list" v-if="props.from == 'taskPerson'">
              <view class="tag" style="padding-left: 24rpx; padding-top: 10rpx">
                <wd-tag
                  :bg-color="getDept(item)['color']"
                  :color="getDept(item)['color']"
                  plain
                  style="font-size: 26rpx; margin-right: 10rpx"
                  @click="selectDept(item)"
                  v-for="(item, index) in deptList"
                  :key="index"
                >
                  {{ getDept(item)['label'] }}
                </wd-tag>
              </view>
            </view>
            <view class="search-results" v-if="state.vagueResults.length">
              <view
                v-for="(item, index) in state.vagueResults"
                :key="index"
                class="row"
                :class="ids.includes(item.personCode) ? 'text-blue' : ''"
                @click="checkThis(item)"
              >
                <span class="name">{{ item.personCode }}</span>
                <span class="dept">{{ item.deptName }}</span>
                <span class="user">{{ item.personName }}</span>
              </view>
            </view>
            <view v-else class="no-task">
              <image src="../static/noman.png"></image>
              <view>没有成员</view>
            </view>
          </swiper-item>
          <swiper-item v-if="false">
            <view class="content">
              <scroll-view
                class="tabs-wrap"
                scroll-x="true"
                scroll-with-animation="true"
                :scroll-left="state.sroLeft"
              >
                <view class="tabs" :style="state.sroSty">
                  <view
                    class="item"
                    :class="item == '请选择' ? 'text-grey' : ''"
                    v-for="(item, index) in state.tabs"
                    :key="index"
                    @tap="tabThis($event, index)"
                  >
                    {{ item }}
                    <text
                      class="icon cuIcon-right text-gray"
                      v-if="state.tabs.length - 1 > index"
                    ></text>
                  </view>
                  <view class="son bg-gradual-blue" :style="state.style"></view>
                </view>
              </scroll-view>
              <view class="options">
                <view
                  class="option"
                  v-for="(item, index) in state.options[state.posInd]"
                  :key="index"
                  :class="
                    ids.includes(item.personCode) || state.tabs.includes(item.name)
                      ? 'text-blue'
                      : ''
                  "
                  @tap="pickThis($event, item)"
                >
                  {{ item.name || item.personName }}
                  <text v-if="ids.includes(item.personCode)" class="cuIcon-check"></text>
                </view>
                <view
                  class="no-task"
                  v-if="
                    state.loaded &&
                    (!state.options[state.posInd] || !state.options[state.posInd].length)
                  "
                >
                  此部门没有成员
                </view>
              </view>
            </view>
          </swiper-item>
        </swiper>
      </view>
    </wd-popup>
  </view>
</template>

<script lang="ts" setup name="leaguerPicker">
import { queryDeptList, queryDeptAllList, queryUserList } from '@/service/task';
import cache from '@/utils/cache';
import { strLen } from '../utils/util';
import { useDict } from '@/hooks/dict';
const { task_person_dept_list } = useDict('task_person_dept_list');
const emit = defineEmits(['hideModal', 'checkLeaguer']);
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  nop: {
    type: Number,
    default: -1,
  },
  deptId: {
    // 是否从当前 所传部门选择
    type: String,
    default: '',
  },
  filtration: {
    // 是否过滤离职人员
    type: Boolean,
    default: false,
  },
  returnDeptName: {
    type: Boolean,
    default: false,
  },
  checked: {
    type: Array,
    default: () => [],
  },
  allDept: {
    type: Boolean,
    default: false,
  },
  from: {
    type: String,
    default: '',
  },
});
const tenantId = cache.getTenant();
const state = reactive({
  loaded: false,
  style: {
    left: '',
    width: '',
  },
  sroSty: {
    width: '',
  },
  depts: [],
  tabs: ['请选择'],
  posInd: 0,
  options: [],
  sroLeft: 0,
  realName: '',
  vagueResults: [],
  cache: null,
  scrollLeft: 100,
  showDia: false,
  arr: [],
  _w: 0,
});
const ids = computed(() => {
  return props.checked.map((el: any) => {
    return el.personCode;
  });
});
watch(
  () => props.checked,
  (val) => {
    state.cache = state.cache || JSON.parse(JSON.stringify(val));
  },
  { immediate: true, deep: true },
);
watch(
  () => props.show,
  (val) => {
    state.showDia = val;
    if (val) {
      if (props.deptId) onSearchInput();
    }
  },
  { immediate: true, deep: true },
);
watch(
  () => props.deptId,
  (val) => {
    // console.log(val, 2222222222222);
  },
  { immediate: true, deep: true },
);
watch(
  () => props.from,
  (val) => {
    // console.log(val, 2222222222222);
  },
  { immediate: true },
);
const deptList = ref([
  // {
  //   value: '1805434137486417922',
  //   label: '研发部',
  // },
  // {
  //   value: '1805434138107174913',
  //   label: '品控部',
  // },
  // {
  //   value: '1805434119119560705',
  //   label: '销售',
  // },
  // {
  //   value: '1805434116602978306',
  //   label: '采购',
  // },
  // {
  //   value: '',
  //   label: '其他',
  // },
]);
watch(
  () => [task_person_dept_list.value, props.from],
  ([val, val1]) => {
    if (val && val.length && val1 == 'taskPerson') {
      deptList.value = JSON.parse(JSON.stringify(val));
      deptList.value.push({
        value: '',
        label: '其他',
      });
      // if (props.from == 'taskPerson') {
      current.value = deptList.value[0];
      onSearchInput();
      // }
    } else {
      current.value = {};
    }
  },
);
const current = ref(null);
const selectDept = (item) => {
  current.value = item;
  onSearchInput();
};
const getDept = (item) => {
  if (!current.value) {
    current.value = deptList.value[0];
  }
  if (current.value.value == item.value) {
    return {
      value: item.value,
      label: item.label,
      color: '#108ee9',
    };
  } else {
    return {
      value: item.value,
      label: item.label,
      color: '#d46b08',
    };
  }
};
onMounted(() => {});
// if (props.from == 'taskPerson') {
//   current.value = deptList.value[0];
// }
const onSearchInput = (e?) => {
  state.realName = e ? e.detail.value : state.realName || '';

  const data = { personName: state.realName, tenantId };
  // 是否过滤离职人员
  if (props.filtration) {
    Object.assign(data, { employmentState: 10 });
  }
  if (props.deptId) {
    // 获取 部门id下的所有人员
    Object.assign(data, { page: 1, limit: 200, deptId: props.deptId });
  }
  if (props.from == 'taskPerson' && current.value?.value) {
    Object.assign(data, { page: 1, limit: 200, deptId: current.value.value });
  }
  console.log(data, 1111111111);

  queryUserList(data)
    .then((res) => {
      state.vagueResults = res.data.records;
    })
    .catch((err) => {});
};
const hideModal = () => {
  // emit('checkLeaguer', state.cache);
  state.cache = null;
  emit('hideModal');
  state.showDia = false;
};
const makeSure = () => {
  emit('checkLeaguer', props.checked);
  state.cache = null;
  hideModal();
};
const cancelThis = (index) => {
  props.checked.splice(index, 1);
};
const tabThis = (e, index) => {
  state.posInd = index;
  count(e.target.offsetLeft);
};
const getById = (list, id) => {
  list.forEach((me) => {
    if (id === me.id) {
      state.arr = me.children ? me.children : [];
    } else if (me.children && me.children.length) {
      getById(me.children, id);
    }
  });
};
const getSonOptions = (id) => {
  state.arr = [];
  console.log(state.depts);

  getById(state.depts, id);
  const opt = state.arr;
  if (opt.length) {
    state.options[state.posInd] = opt;
  } else {
    // 异步加载
    state.loaded = false;
    const data = { deptId: id, limit: 200, tenantId };
    // 是否过滤离职人员
    if (props.filtration) {
      Object.assign(data, { status: 1, employmentState: 10 });
    }
    queryUserList(data)
      .then((res) => {
        state.options.splice(state.posInd, 1, res.data.records);
        state.loaded = true;
      })
      .catch((err) => {
        console.log(err);
      });
  }
};
const checkThis = (option) => {
  const i = ids.value.indexOf(option.personCode);
  if (i !== -1) {
    props.checked.splice(i, 1);
    state.realName = '';
  } else {
    if (props.nop !== -1 && props.checked.length >= props.nop) {
      uni.showToast({
        title: `最多可选${props.nop}人`,
        icon: 'none',
      });
      return;
    }
    const { personName, personCode, realName, id, tenantId, deptName, deptId } = option;
    const item = props.returnDeptName
      ? { tenantId, deptName, personName, realName, id, deptId, personCode }
      : { personName, realName, id, personCode };
    props.checked.push({ ...item });
    state.realName = '';
    state.scrollLeft = 1000;
  }
};

const pickThis = (e, option) => {
  const howmany = state.tabs.length - state.posInd;
  // 如果是部门
  if (!option.personName) {
    if (state.tabs.includes(option.name)) {
      state.posInd = ++state.posInd;
    } else {
      state.tabs.splice(state.posInd, howmany > 0 ? howmany : 1, option.name, '请选择');
      state.posInd = state.tabs.length - 1;
      getSonOptions(option.id);
    }
  } else {
    checkThis(option);
  }

  count();
};
const count = (left?) => {
  let total = 0;
  let w = 0;
  console.log(state.tabs, 1123);

  state.tabs.forEach((t, i) => {
    console.log(t, i);

    w += strLen(t) + 2;
    if (i < state.posInd) {
      total += strLen(t) + 2;
    }
  });

  state.sroSty = {
    width: `${w}em`,
  };

  state.style = {
    left: `${total}em`,
    width: `${strLen(state.tabs[state.posInd])}em`,
  };

  setTimeout(() => {
    if (left || left === 0) {
      state.sroLeft = left - state._w / 2;
    } else {
      state.sroLeft = state.sroLeft += state._w;
    }
  }, 300);
};
const getData = (e) => {
  console.log(e, 11112);

  if (e.detail.current === 1 && !state.depts.length) {
    nextTick(() => {
      (props.allDept ? queryDeptAllList : queryDeptList)()
        .then((res) => {
          state.depts = res.data;
          const parent = res.data.map((me) => {
            return { name: me.name, id: me.id };
          });
          state.options.splice(0, 1, parent);
          count();
        })
        .catch((err) => {
          // this.$error(err.data.msg);
        });
    });
  }
};
</script>

<style scoped lang="scss">
.cu-bar {
  // padding: 10rpx 20rpx;
  position: relative;
  align-items: center;
  justify-content: space-between;
  min-height: 50px;
  border-bottom: 1rpx solid #f1f1f1;
}

:deep(.cu-modal) {
  height: 60vh;
  border-radius: 20rpx;
}
.cu-bar .action {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 50px;
  min-height: 50px;
  margin-right: 0;
  font-size: 30rpx;
}

.checked {
  display: flex;
  // width: 100%;
  padding: 0 30rpx;
  font-size: 28rpx;
  line-height: 80rpx;
  text-align: left;
}

.checked uni-scroll-view {
  flex: 1;
  max-width: calc(100% - 160rpx);
  white-space: nowrap;
}

.checked text {
  margin-right: 20rpx;
  white-space: nowrap;
}

.swiper {
  height: calc(100% - 100rpx);
}

.search {
  height: 80rpx;
  padding: 0 15rpx;
  margin: 0 30rpx;
  font-size: 28rpx;
  text-align: left;
  border: 1rpx solid #f1f1f1;
  border-radius: 10rpx;
}

.content {
  padding: 0 30rpx;
  font-size: 32rpx;
}

.tabs-wrap {
  width: 100%;
}

.tabs {
  position: relative;
  height: 90rpx;
  line-height: 90rpx;
  text-align: left;
}

.tabs .item {
  display: inline-block;
  font-weight: 100;
}

.text-grey,
.line-grey,
.lines-grey {
  color: #8799a3;
}

.icon {
  display: inline-block;
  width: 2em;
  text-align: center;
}

.tabs .son {
  position: absolute;
  bottom: 0;
  height: 8rpx;
  transition: all 0.6s;
}

.bg-gradual-blue {
  color: #fff;
  background-image: linear-gradient(45deg, #0081ff, #1cbbb4);
}
/* 	.indicate{
		height: 8rpx;
		position: relative;
	}
	.indicate .son{
		height:8rpx;
		position: absolute;
		transition: all .6s;
	} */
.options {
  height: 600rpx;
  padding: 30rpx 0;
  overflow-y: scroll;
  text-align: left;
  transition: all 0.3s;
}

.option {
  display: flex;
  justify-content: space-between;
  font-weight: 100;
  line-height: 80rpx;
  border-top: 1rpx solid #f8f8f8;
}

.options .option:first-child {
  border-top: none;
}

.cu-dialog {
  width: 90vw;
  height: 60vh;
  max-height: 920rpx;
  padding: 10rpx 0;
  font-size: 26rpx;
}

.no-task {
  height: calc(100% - 110rpx);
  font-size: 24rpx;
  color: #8a8a8a;
  text-align: center;
  letter-spacing: 2rpx;
}

.no-task image {
  width: 100rpx;
  height: 100rpx;
  margin-top: 100rpx;
}

.search-results {
  height: calc(100% - 150rpx);
  padding: 0 35rpx;
  margin-top: 30rpx;
  overflow-y: scroll;
}

.search-results .row {
  display: flex;
  line-height: 80rpx;
  text-align: left;
  border-top: 1rpx solid #f1f1f1;
}

.search-results .row:first-child {
  border-top: none;
}

.search-results .row .name {
  width: 180rpx;
}

.search-results .row .user {
  width: 180rpx;
}

.search-results .row .dept {
  flex: 1;
}
</style>
